﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace CellarDoor.Gui.Controller
{
    public class UiControllerCollection : ReadOnlyCollection<UiController>
    {
        private List<UiController> list;
        private List<UiController> toUpdate;

        public UiControllerCollection()
            : base(new List<UiController>())
        {
            list = this.Items as List<UiController>;
            toUpdate = new List<UiController>();
        }

        public UiControllerCollection(IEnumerable<UiController> controllers)
            : base(new List<UiController>())
        {
            list = this.Items as List<UiController>;
            toUpdate = new List<UiController>();

            list.AddRange(controllers);
        }

        public UiControllerCollection(params UiController[] controllers)
            : base(new List<UiController>())
        {
            list = this.Items as List<UiController>;
            toUpdate = new List<UiController>();

            list.AddRange(controllers);
        }

        public void Update(float dt)
        {
            if (list.Count > 0)
            {
                toUpdate.AddRange(list);

                foreach (var item in toUpdate)
                {
                    item.Update(dt);
                }
                toUpdate.Clear();
            }
        }

        public UiController Add(UiController controller)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }
            list.Add(controller);

            return controller;
        }

        public UiController Remove(UiController controller)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }
            if (list.Contains(controller))
            {
                list.Remove(controller);
            }

            return controller;
        }

        public void RemoveByType<T>() where T : UiController
        {
            List<UiController> toRemove = new List<UiController>();

            foreach (var item in list)
            {
                if (item is T)
                {
                    toRemove.Add(item);
                }
            }
        }
    }
}
